<?php

require_once 'mysql.php';

function addTrip($tripName) {
	mysql_query ( "INSERT INTO `trips` 
						   SET `name` = '" . $tripName . "'" );
	return mysql_insert_id ();
}

function deleteTrip($tripID) {
	mysql_query ( "DELETE FROM `trips` 
					     WHERE `id` = '" . $tripID . "'" );
}

function getTrips() {
	
	$trips = array ();
	
	$query = mysql_query ( "SELECT * FROM `trips`" );
	
	while ( $trip = mysql_fetch_array ( $query ) )
		$trips [] = array ("id" => $trip ["id"], "name" => $trip ["name"] );
	
	return $trips;
}

function getTrip($tripID) {
	
	$result = mysql_query ( "SELECT * FROM `trips`
								     WHERE `id` = '" . $tripID . "'" );
	
	if(mysql_num_rows($result) > 0) {
		return mysql_fetch_array($result);
	} else {
		return null;
	}
	
}

function addPoint($tripID, $longitude, $latitude, $type) {
	mysql_query ( "INSERT INTO `points` 
						   SET `trip_id` = '" . $tripID . "', 
							   `longitude` = '" . $longitude . "', 
							   `latitude` = '" . $latitude . "',
							   `type` = '" . $type . "'" );
	return mysql_insert_id ();
}

function deletePoint($pointID) {
	mysql_query ( "DELETE FROM `points`
					     WHERE `id` = '" . $pointID . "'" );
}

function getPoints($tripID, $type) {
	
	$points = array ();
	
	if ($type == "pin" || $type == "path") {
		
		$query = mysql_query ( "SELECT * FROM `points` 
	 								WHERE `trip_id` = '" . $tripID . "'
	 								  AND `type` = '" . $type . "'
	 							 ORDER BY id ASC" );
		
		while ( $point = mysql_fetch_array ( $query ) )
			$points [] = array ("id" => $point ["id"], "longitude" => $point ["longitude"], "latitude" => $point ["latitude"], "type" => $point ["type"] );
	
	}
	
	return $points;
}

function attachNotes($pointsArray) {
	
	foreach ( $pointsArray as $k => $v ) {
		if ($v ["type"] == "pin") {
			
			$result = mysql_query ( "SELECT * FROM `notes` 
											 WHERE `point_id` = '" . $v ["id"] . "' 
											 LIMIT 1" );
			
			if (mysql_num_rows ( $result ) > 0) {
				$note = mysql_fetch_array ( $result );
				$pointsArray [$k] ["note_text"] = $note ["text"];
			}
		}
	}
	
	return $pointsArray;

}

function addNote($pointID, $text) {
	mysql_query ( "INSERT INTO `notes` 
						   SET `point_id` = '" . $pointID . "',
						 	   `text` = '" . $text . "'" );
	return mysql_insert_id ();
}

function deleteNote($noteID) {
	mysql_query ( "DELETE FROM `notes`
					     WHERE `id` = '" . $noteID . "'" );
}

?>